那个<!doctype html>
<html>

	<head>
		<meta charset="utf-8">
		<title></title>
		<meta name="viewport"
			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="../css/mui.css" rel="stylesheet" />
		<link rel="stylesheet" href="../css/icons.css">
		<link rel="stylesheet" href="../css/chat.css">
	</head>

	<body>
		<header class="mui-bar mui-bar-nav">
			<h1 class="mui-title">AI智能顾问</h1>
		</header>
		<!-- 聊天内容区域 -->
		<div class="chat-container">
		</div>

		<!-- 底部输入区域 -->
		<div class="input-area">
			<div class="input-container">
				<div class="input-field">
					<input type="text" placeholder="请输入您的农业相关问题...">
				</div>
				<button class="send-button" style="display: ;">
					<i class="icon icon-paper-plane"
						style="width: 20px; height: 20px; display: flex; justify-content: center; align-items: center;"></i>
				</button>
				<button class="stop-button" style="display: none;">
					<span class="mui-icon mui-icon-close"
						style="width: 20px; height: 20px; display: flex; justify-content: center; align-items: center;"></span>
				</button>
			</div>
		</div>
		<script src="../js/mui.js"></script>
		<script src="../js/request.js"></script>
		<script src="../js/storage.js"></script>
		<script>
			let user = userCache.getUser();
			let userId = user.userId;
			let assistantMsgIndex = 0;
			// let baseUrl = 'http://192.168.0.101:5502'; 
			let baseUrl = localStorage.getItem("ip");
			let eventSource = null;

			mui.init()

			window.addEventListener('refresh', function(event) {
				refresh()
			});

			// 发送按钮点击事件
			document.querySelector('.send-button').addEventListener('click', function() {
				const input = document.querySelector('input');
				const message = input.value.trim();
				if (message === '') {
					mui.toast('请输入您的问题');
					return;
				}
				document.querySelector('.send-button').style.display = 'none';
				document.querySelector('.stop-button').style.display = '';
				sendMessage();
			});

			document.querySelector('.stop-button').addEventListener('click', function() {
				if (eventSource) {
					eventSource.close();
				}
				// 移除打字指示器
				const typingIndicators = document.querySelectorAll('.typing-indicator');
				if (typingIndicators[typingIndicators.length - 1]) {
					typingIndicators[typingIndicators.length - 1].style.display = 'none';
					document.querySelector('.send-button').disabled = false;
				}
				document.querySelector('.send-button').style.display = '';
				document.querySelector('.stop-button').style.display = 'none';
			});

			function refresh() {
				if (eventSource) {
					eventSource.close();
				}
				assistantMsgIndex = 0;
				const chatContainer = document.querySelector('.chat-container');
				const height = window.innerHeight;
				chatContainer.style.height = `${height - 100}px`;
				chatContainer.innerHTML = '';
				document.querySelector('.send-button').style.display = '';
				document.querySelector('.stop-button').style.display = 'none';
				getHistoryMsg();
			}

			refresh()

			//获取最新的20条历史消息
			function getHistoryMsg() {
				let params = {
					"userId": userId,
					"pageNum": 1,
					"pageSize": 20,
					"orderByColumn": "create_time",
					"isAsc": "desc",
				}
				request.get('/system/chatMessages/list', params, (resp) => {
					console.log('获取历史消息成功')
					let list = resp.rows;
					list = list.reverse();
					for (let i = 0; i < list.length; i++) {
						assistantMsgIndex++;
						addMessage(list[i].role, list[i].content, true);
					}
				}, (error, thrown) => {
					//发生错误时，回调
					console.error('调用服务端历史聊天记录失败', error)
				})
			}

			// 发送消息
			function sendMessage() {
				const input = document.querySelector('input');
				const message = input.value.trim();
				if (!message) return;

				// 添加用户消息到界面
				addMessage('user', message);
				input.value = '';

				// 保存聊天记录
				let data = {
					userId: userId, 
					content: message,
					role: 'user',
				}
				request.post("/system/chatMessages", data, (resp) => {
					console.log('调用服务端保存聊天记录成功')
				}, (error, thrown) => {
					//发生错误时，回调
					console.error('调用服务端保存聊天记录失败', error)
				})

				assistantMsgIndex++;
				addMessage('assistant', '');

				// 建立SSE连接
				eventSource = new EventSource(`${baseUrl}/api/chat/stream?userId=${userId}&question=${message}`);
				eventSource.onmessage = function(event) {
					// console.log('AI回复:', event.data);
					addMessage('assistant', event.data);
				};
				eventSource.onerror = function(err) {
					console.error('SSE error:', JSON.stringify(err));
					eventSource.close();
					document.querySelector('.send-button').style.display = '';
					document.querySelector('.stop-button').style.display = 'none';
				};
			}

			function addMessage(role, message, history = false) {
				// 创建用户消息元素
				const chatContainer = document.querySelector('.chat-container');
				if (role === 'user') {
					const input = document.querySelector('input');
					const userMessage = document.createElement('div');
					userMessage.className = 'message-container user';
					userMessage.innerHTML = `
					        <div class="chat-bubble user-message">
					            <p>${message}</p>
					        </div>
					        <div class="message-avatar user-avatar">
					            <i class="icon icon-user avatar-icon"></i>
					        </div>
					    `;

					chatContainer.appendChild(userMessage);
					input.value = '';

					// 滚动到底部
					chatContainer.scrollTop = chatContainer.scrollHeight;
				}
				if (role === 'assistant') {
					let newTypingMessage = document.getElementById('new-typing-message-' + assistantMsgIndex);
					if (!newTypingMessage) {
						const typingDiv = document.createElement('div');
						typingDiv.className = 'message-container';
						if (!history) {
							typingDiv.innerHTML = `
							                        <div class="message-avatar assistant-avatar">
							                            <i class="icon icon-leaf avatar-icon"></i>
							                        </div>
							                        <div class="chat-bubble assistant-message">
							                            <p id="new-typing-message-${assistantMsgIndex}"></p>
							                            <div class="typing-indicator mt-2">
							                                <span></span>
							                                <span></span>
							                                <span></span>
							                            </div>
							                        </div>
							                    `;
						} else {
							typingDiv.innerHTML = `
							                        <div class="message-avatar assistant-avatar">
							                            <i class="icon icon-leaf avatar-icon"></i>
							                        </div>
							                        <div class="chat-bubble assistant-message">
							                            <p id="new-typing-message-${assistantMsgIndex}"></p>
							                        </div>
							                    `;
						}
						chatContainer.appendChild(typingDiv);
						if (history) {
							newTypingMessage = document.getElementById('new-typing-message-' + assistantMsgIndex);
							newTypingMessage.innerHTML = message;
						}
						chatContainer.scrollTop = chatContainer.scrollHeight;
					} else {
						if (message) {
							if (!message.toUpperCase().includes('<EOF>')) { //输出未结束
								newTypingMessage.innerHTML = message;
								chatContainer.scrollTop = chatContainer.scrollHeight;
							} else {
								if (!history) {
									// 移除打字指示器
									const typingIndicators = document.querySelectorAll('.typing-indicator');
									if (typingIndicators[typingIndicators.length - 1]) {
										typingIndicators[typingIndicators.length - 1].style.display = 'none';
										document.querySelector('.send-button').disabled = false;
									}
								}
							}
						}
					}
				}
			}

			// 获取当前时间
			function getCurrentTime() {
				const now = new Date();
				const hours = now.getHours().toString().padStart(2, '0');
				const minutes = now.getMinutes().toString().padStart(2, '0');
				return `${hours}:${minutes}`;
			}

			// 输入框回车键发送
			document.querySelector('input').addEventListener('keypress', function(e) {
				if (e.key === 'Enter') {
					document.querySelector('.send-button').click();
				}
			});
		</script>
	</body>

</html>